﻿import mx.utils.Delegate;

class SpaceShipGameLite extends MovieClip {	
	var __ship:Ship;
	
	var __keyListener:Object;
	
	function SpaceShipGameLite() {
		init();
	}
	
	function init():Void{
		createShip();
		
		__keyListener = {onKeyDown: Delegate.create(this, keyDownHandler)
						, onKeyUp: Delegate.create(this, keyUpHandler)};
		Key.addListener(__keyListener);
		
		onEnterFrame = gameOnEnterFrame;
	}
	
	function gameOnEnterFrame():Void{
		var ship_mc:MovieClip = this["ship_mc"];
		
		if(ship_mc._x>Stage.width)ship_mc._x-=Stage.width;
		if(ship_mc._x<0)ship_mc._x+=Stage.width;
		if(ship_mc._y<0)ship_mc._y=0;
		
		if(ship_mc._y>Stage.height){
			ship_mc._y=Stage.height;
			
			gameover();
		}
	}
	
	function createShip():Void{
		__ship = new Ship(this.createEmptyMovieClip("ship_mc", 2));
		this["ship_mc"]._x = Stage.width / 2;
		this["ship_mc"]._y = Stage.height / 2;
	}
	
	function keyDownHandler():Void{
		switch(Key.getCode()){
			case Key.LEFT:
				__ship.rotate(-1);
				break;
			case Key.RIGHT:
				__ship.rotate(1);
				break;
			case Key.UP:
				__ship.move(true);
				break;
		}
	}

	function keyUpHandler():Void{
		switch(Key.getCode()){
			case Key.LEFT:
			case Key.RIGHT:
				__ship.rotate(0);
				break;
			case Key.UP:
				__ship.move(false);
				break;
		}
	}
	
	function gameover():Void{
		__ship.G = 0;
		Key.removeListener(__keyListener);
		onEnterFrame = null;
		
		var ship_roration:Number = __ship.getRotation();
		var ship_movingSpeed:Number = __ship.getMovingSpeed();
		trace("rotation=" + ship_roration + ", movingSpeed=" + ship_movingSpeed);
		
		if(Math.abs(ship_roration)<10 && ship_movingSpeed<3){
			this.lineStyle(5, 0x0000ff, 80);
			this.moveTo(0, Stage.height/2);
			this.lineTo(Stage.width/2, Stage.height);
			this.lineTo(Stage.width, 0);
		}else{
			this.lineStyle(5, 0xff0000, 80);
			this.moveTo(0, 0);
			this.lineTo(Stage.width, Stage.height);
			this.moveTo(Stage.width, 0);
			this.lineTo(0, Stage.height);
		}
	}
}
